<template>
  <div>
    <div class="weui-search-bar" id="search_bar" :class="{'weui-search-bar_focusing':is_focusing}">
      <form class="weui-search-bar__form" @submit.prevent="on_form_submit">
        <div class="weui-search-bar__box">
          <i class="weui-icon-search"></i>
          <input type="search" class="weui-search-bar__input" id="search_input" :placeholder="placeholder"
                 v-model="search_text"
                 @focus="is_focusing=true" @blur="is_focusing=false"/>
          <a href="javascript:" class="weui-icon-clear" id="search_clear" @click.stop="search_text=''"></a>
        </div>
        <label for="search_input" class="weui-search-bar__label" id="search_text" v-show="search_text==''">
          <i class="weui-icon-search"></i>
          <span>{{placeholder}}</span>
        </label>
      </form>
      <a href="javascript:" class="weui-search-bar__cancel-btn" id="search_cancel" @click.stop="on_cancel">
        {{cancel_text}}
      </a>
    </div>
    <div class="weui-cells weui-cells_access search_show" id="search_show" v-show="search_text!=''"
         style="margin-top:0;font-size:14px;">
      <div class="weui-cell" v-for="word in list" @click="on_word_click(word)">
        <div class="weui-cell__bd weui-cell_primary">
          <p>{{word}}</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  export default {
    props: {
      list: {
        type: Array,
        default() {
          return ['word', 'word']
        }
      },
      placeholder: {
        type: String,
        default: '搜索'
      },
      cancel_text: {
        type: String,
        default: '取消'
      },
      cancel_icon: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        is_focusing: false,
        search_text: ''
      }
    },
    watch: {
      search_text(value) {
        this.$emit('on-input', value)
      }
    },
    methods: {
      on_word_click(word) {
        this.search_text = word.substring(word.indexOf(']') + 1)
        this.$nextTick(() => {
          this.$emit('on-search')
        })
      },
      on_form_submit() {
        document.getElementById('search_input').blur()
        this.$emit('on-search')
      },
      on_cancel() {
        if (this.cancel_text == '取消') {
          this.search_text = ''
        } else {
          this.$emit('on-cancel')
        }
      }
    }
  }
</script>

<style>
  @import '~weui/dist/style/weui.min.css';
</style>
